<template>
    <div class="posts-page">
        <!-- Header -->
        <van-nav-bar title="My Posts" left-text="Back" left-arrow @click-left="$router.back()">
            <template #right>
                <van-icon name="plus" @click="createPost" />
            </template>
        </van-nav-bar>

        <!-- Stats Overview -->
        <div class="posts-stats">
            <div class="stat-item">
                <div class="stat-number">{{ userPosts.length }}</div>
                <div class="stat-label">Total Posts</div>
            </div>
            <div class="stat-item">
                <div class="stat-number">{{ totalLikes }}</div>
                <div class="stat-label">Total Likes</div>
            </div>
            <div class="stat-item">
                <div class="stat-number">{{ totalComments }}</div>
                <div class="stat-label">Total Comments</div>
            </div>
        </div>

        <!-- Posts List -->
        <div class="posts-list">
            <div v-for="post in userPosts" :key="post.id" class="post-item" @click="viewPost(post.id)">
                <div class="post-header">
                    <div class="post-meta">
                        <span class="post-date">{{ formatDate(post.createdAt) }}</span>
                        <van-tag type="primary">
                            {{ post.type }}
                        </van-tag>
                    </div>
                    <van-icon name="more-o" @click.stop="showPostActions(post)" />
                </div>

                <div class="post-content">
                    <h3 class="post-title">{{ post.title }}</h3>
                    <p class="post-excerpt">{{ post.excerpt }}</p>

                    <div v-if="post.images && post.images.length > 0" class="post-images">
                        <img v-for="(image, index) in post.images.slice(0, 3)" :key="index" :src="image"
                            :alt="`Post image ${index + 1}`" class="post-image" />
                        <div v-if="post.images.length > 3" class="more-images">
                            +{{ post.images.length - 3 }}
                        </div>
                    </div>
                </div>

                <div class="post-stats">
                    <div class="stat">
                        <van-icon name="good-job-o" />
                        <span>{{ post.likes }}</span>
                    </div>
                    <div class="stat">
                        <van-icon name="chat-o" />
                        <span>{{ post.comments }}</span>
                    </div>
                    <div class="stat">
                        <van-icon name="eye-o" />
                        <span>{{ post.views }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Empty State -->
        <div v-if="userPosts.length === 0" class="empty-state">
            <van-empty description="No posts yet">
                <van-button type="primary" size="small" @click="createPost">
                    Create Your First Post
                </van-button>
            </van-empty>
        </div>

        <!-- Post Actions Sheet -->
        <van-action-sheet v-model:show="showActions" :actions="postActions" @select="onActionSelect"
            cancel-text="Cancel" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()

// Post interface
interface Post {
    id: number
    title: string
    excerpt: string
    content: string
    type: string
    likes: number
    comments: number
    views: number
    createdAt: number
    images: string[]
}

// Mock user posts data
const userPosts = ref<Post[]>([
    {
        id: 1,
        title: 'My First Job Interview Experience',
        excerpt: 'Just had my first job interview after completing the training sessions. Here are my thoughts and tips...',
        content: 'Full content here...',
        type: 'Experience',
        likes: 24,
        comments: 8,
        views: 156,
        createdAt: Date.now() - 2 * 24 * 60 * 60 * 1000, // 2 days ago
        images: ['/api/placeholder/300/200', '/api/placeholder/300/200']
    },
    {
        id: 2,
        title: 'Tips for Building Confidence in Social Situations',
        excerpt: 'After months of practice, I\'ve learned some valuable techniques that really work...',
        content: 'Full content here...',
        type: 'Tips',
        likes: 45,
        comments: 12,
        views: 289,
        createdAt: Date.now() - 5 * 24 * 60 * 60 * 1000, // 5 days ago
        images: []
    },
    {
        id: 3,
        title: 'Overcoming Social Anxiety: My Journey',
        excerpt: 'Sharing my personal story of how I overcame social anxiety through consistent practice...',
        content: 'Full content here...',
        type: 'Story',
        likes: 67,
        comments: 23,
        views: 445,
        createdAt: Date.now() - 7 * 24 * 60 * 60 * 1000, // 1 week ago
        images: ['/api/placeholder/300/200']
    }
])

// Computed properties
const totalLikes = computed(() => {
    return userPosts.value.reduce((sum, post) => sum + post.likes, 0)
})

const totalComments = computed(() => {
    return userPosts.value.reduce((sum, post) => sum + post.comments, 0)
})

// Action sheet
const showActions = ref(false)
const selectedPost = ref<Post | null>(null)

const postActions = [
    { name: 'Edit Post', value: 'edit' },
    { name: 'Share Post', value: 'share' },
    { name: 'Delete Post', value: 'delete', color: '#ee0a24' }
]

// Methods
const createPost = () => {
    router.push('/community/publish')
}

const viewPost = (postId: number) => {
    router.push(`/community/post/${postId}`)
}

const showPostActions = (post: Post) => {
    selectedPost.value = post
    showActions.value = true
}

const onActionSelect = (action: any) => {
    if (!selectedPost.value) return

    switch (action.value) {
        case 'edit':
            editPost(selectedPost.value.id)
            break
        case 'share':
            sharePost(selectedPost.value)
            break
        case 'delete':
            deletePost(selectedPost.value.id)
            break
    }
    showActions.value = false
}

const editPost = (postId: number) => {
    router.push(`/community/publish?edit=${postId}`)
}

const sharePost = (post: Post) => {
    if (navigator.share) {
        navigator.share({
            title: post.title,
            text: post.excerpt,
            url: `${window.location.origin}/community/post/${post.id}`
        })
    } else {
        // Fallback for browsers that don't support Web Share API
        navigator.clipboard.writeText(`${window.location.origin}/community/post/${post.id}`)
        showToast('Link copied to clipboard!')
    }
}

const deletePost = async (postId: number) => {
    const result = await showConfirmDialog({
        title: 'Delete Post',
        message: 'Are you sure you want to delete this post? This action cannot be undone.',
        confirmButtonText: 'Delete',
        confirmButtonColor: '#ee0a24'
    })

    if (result) {
        const index = userPosts.value.findIndex(post => post.id === postId)
        if (index > -1) {
            userPosts.value.splice(index, 1)
            showToast('Post deleted successfully')
        }
    }
}

const formatDate = (timestamp: number) => {
    const now = Date.now()
    const diff = now - timestamp
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
        return 'Today'
    } else if (days === 1) {
        return 'Yesterday'
    } else if (days < 7) {
        return `${days} days ago`
    } else {
        return new Date(timestamp).toLocaleDateString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric'
        })
    }
}
</script>

<style lang="scss" scoped>
.posts-page {
    min-height: 100vh;
    background: #f8f9fa;
}

.posts-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    padding: 16px;
    background: white;
    margin-bottom: 8px;

    .stat-item {
        text-align: center;

        .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #323233;
            margin-bottom: 4px;
        }

        .stat-label {
            font-size: 12px;
            color: #969799;
        }
    }
}

.posts-list {
    padding: 0 16px 16px;

    .post-item {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .post-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .post-meta {
                display: flex;
                align-items: center;
                gap: 8px;

                .post-date {
                    font-size: 12px;
                    color: #969799;
                }
            }
        }

        .post-content {
            margin-bottom: 12px;

            .post-title {
                font-size: 16px;
                font-weight: 600;
                color: #323233;
                margin: 0 0 8px 0;
                line-height: 1.4;
            }

            .post-excerpt {
                font-size: 14px;
                color: #646566;
                line-height: 1.5;
                margin: 0 0 12px 0;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
            }

            .post-images {
                display: flex;
                gap: 8px;
                position: relative;

                .post-image {
                    width: 60px;
                    height: 60px;
                    border-radius: 8px;
                    object-fit: cover;
                }

                .more-images {
                    width: 60px;
                    height: 60px;
                    border-radius: 8px;
                    background: rgba(0, 0, 0, 0.6);
                    color: white;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                    font-weight: 500;
                }
            }
        }

        .post-stats {
            display: flex;
            gap: 16px;

            .stat {
                display: flex;
                align-items: center;
                gap: 4px;
                font-size: 12px;
                color: #969799;

                .van-icon {
                    font-size: 14px;
                }
            }
        }
    }
}

.empty-state {
    padding: 40px 16px;
}
</style>